package base.juc;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 重入锁 和 synchronized 的区别
 * Author: shen qi han
 * Date: 2022/3/19 上午12:21
 */
public class ReentrantLockMain {

    /**
     * fair lock
     *      让锁上 等待时间最长的线程 使用锁的使用权
     *      可以看到结果，是乱序的
     * unFair lock
     *      随机分配 使用权，可能会导致饥饿
     *      可以看到结果，相同的线程是挨在一起的
     */
    boolean fair = false;
    Lock lock = new ReentrantLock(fair);

    class MyThread implements Runnable{
        Integer id;

        public MyThread(Integer id) {
            this.id = id;
        }

        @Override
        public void run() {
            // imitate scene
            try {
                TimeUnit.MILLISECONDS.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // 可重入锁
            // ReentrantLock获得了锁 还可以 重复获取
            for(int i = 0; i < 2; i++){
                lock.lock();
                System.out.println("获得锁的线程: " + this.id);
                lock.unlock();
            }

        }
    }

    /**
     * 公平锁 or 非公平锁
     */
    public void testReentrantLock(){
        int n = 5;
        ExecutorService pool = Executors.newFixedThreadPool(n);
        // 模拟 多个线程 去请求当前锁
        for(int i = 0; i < 5; i++){
            pool.submit(new MyThread(i));
        }
        pool.shutdown();
    }

    Lock lock1 = new ReentrantLock();
    Lock lock2 = new ReentrantLock();

    class MyThread2 implements Runnable{
        Lock firstLock;
        Lock secondLock;

        public MyThread2(Lock firstLock, Lock secondLock){
            this.firstLock = firstLock;
            this.secondLock = secondLock;
        }

        @Override
        public void run() {
            try {
                // 当前没有被中断 则获取锁
                firstLock.lockInterruptibly();
                TimeUnit.MILLISECONDS.sleep(10);
                // 当前没有被中断 则获取锁
                secondLock.lockInterruptibly();
                System.out.println(Thread.currentThread().getName() + "获得锁！");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally{
                // mark if thread interrupt the final's code will not run
                firstLock.unlock();
                secondLock.unlock();
                System.out.println(Thread.currentThread().getName() + "正常运行！");
            }
        }
    }

    /**
     * 解决死锁的问题
     */
    public void deadLock(){
        int n = 2;
        // thread first get lock1 then get lock2
        Thread thread0 = new Thread(new MyThread2(lock1, lock2));
        // thread second get lock2 then get lock1
        Thread thread1 = new Thread(new MyThread2(lock2, lock1));
        thread0.start();
        thread1.start();
        // if we have not any thread interrupt then the resource will dead lcok
        // thread1 interrupt then
        thread0.interrupt();
    }


    public static void main(String[] args) {
        ReentrantLockMain main = new ReentrantLockMain();
//        main.testReentrantLock();
        main.deadLock();
    }


}
